import axios from 'axios'
import { useUserStore } from '../store/user'
import { ElMessage } from 'element-plus'
import router from '../router'

const request = axios.create({
    baseURL: 'http://localhost:3000/api',
    timeout: 5000,
})

request.interceptors.request.use(
    config => {
        const userStore = useUserStore()
        if (userStore.token) {
            config.headers['Authorization'] = `Bearer ${userStore.token}`
            userStore.checkTokenExpiration()
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

request.interceptors.response.use(
    response => response.data,
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    ElMessage.error('登录已过期，请重新登录')
                    useUserStore().logout()
                    break
                case 403:
                    ElMessage.error('没有权限执行此操作')
                    break
                default:
                    ElMessage.error(error.response.data.message || '请求失败')
            }
        }
        return Promise.reject(error)
    }
)

export default request